package com.zy.cloud.controller;

import com.zy.cloud.entity.CommonResult;
import com.zy.cloud.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName: UserController
 * @Description: #TODO
 * @Author: yanzy
 * @Date: 2021/3/1 23:08
 */
@RestController
@Slf4j
public class UserZkController {

    private static final String INVOKE_URL = "http://cloud-provider-server";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/user/{id}")
    public CommonResult<User> selectOne(@PathVariable("id") Long id) {

        return restTemplate.getForObject(INVOKE_URL + "/user/" + id, CommonResult.class);
    }

    /**
     * 服务发现
     *
     * @return
     */
    @GetMapping("/discovery")
    public Object discovery() {

        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            log.info("服务element: " + element);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-SERVER");
        for (ServiceInstance instance : instances) {
            log.info(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }

        return this.discoveryClient;
    }
}
